use clap::{App, Arg};
use rand::Rng;
use std::{
  io::{stdout, Error},
  process::exit,
  sync::{
    mpsc,
    mpsc::{Receiver, Sender},
  },
};
use termion::raw::IntoRawMode;

mod input;
mod renderer;

fn main() -> Result<(), Error> {
  let matches = App::new("Fireworks")
    .version("1.0.2")
    .author("Darrien Glasser <me@darrien.dev>")
    .about("A fun terminal fireworks display")
    .arg(
      Arg::with_name("seed")
        .short("s")
        .long("seed")
        .takes_value(true)
        .help("set custom random seed"),
    )
    .get_matches();

  let seed = if let Some(i) = matches.value_of("seed") {
    i.parse::<u64>().unwrap_or_else(|_| {
      eprintln!("Must be a valid number: {}", i);
      exit(1);
    })
  } else {
    rand::thread_rng().gen_range(0, u64::MAX)
  };

  let (sender, receiver): (Sender<bool>, Receiver<bool>) = mpsc::channel();
  let mut stdout = stdout()
    .into_raw_mode()
    .expect("Unable to capture stdout. Exiting.");

  input::capture(sender);
  renderer::start(&mut stdout, receiver, seed);

  Ok(())
}
